package com.qianfeng.rencai.security.handler;

import com.qianfeng.rencai.mapper.SysRoleMapper;
import com.qianfeng.rencai.pojo.SysMenu;
import com.qianfeng.rencai.pojo.SysRole;
import com.qianfeng.rencai.security.bean.BaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by wenka on 2022/3/30 16:41
 *
 * @author wenkaixin
 * @version 1.0
 * @since 1.0
 */
@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    private SysRoleMapper sysRoleMapper;

    @Autowired
    public void setSysRoleMapper(SysRoleMapper sysRoleMapper) {
        this.sysRoleMapper = sysRoleMapper;
    }
    /**
     * @param request
     * @param response
     * @param authentication 认证信息 我们登录的时候返回的对象
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("成功");
        //获取登录方法返回的对象
        BaseUser baseUser = (BaseUser) authentication.getPrincipal();
        baseUser.getUserId();
        //获取到用户的权限
        List<SysRole> roleList = sysRoleMapper.findRoleByUserIdWithMenu(baseUser.getUserId());
        //用户所有的权限
        Set<String> allPermisson = new HashSet<>();
        roleList.forEach(role -> {
            List<SysMenu> menusList = role.getMenuList();
            List<String> permissonList = menusList.stream().map(SysMenu::getPerms).collect(Collectors.toList());
            allPermisson.addAll(permissonList);
        });
        //更新用户的权限,将用户的权限字符串转成security中的权限对象
        List<SimpleGrantedAuthority> authorityList = allPermisson.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        //刷新用户的权限
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(baseUser,authentication.getCredentials(), authorityList));
//        super.onAuthenticationSuccess(request, response, authentication);
    }

}
